package com.andaily.springoauth.web;

import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.andaily.springoauth.service.OauthService;
import com.andaily.springoauth.service.dto.AuthCallbackDto;
import com.andaily.springoauth.service.dto.AuthorizationCodeDto;
import com.andaily.springoauth.service.dto.UserDto;

/**
 * 授权码模式业务处理控制层
 *
 */
@Controller
public class AuthorizationCodeController {

	@Value("#{properties['user-authorization-uri']}")
	private String			userAuthorizationUri;

	@Value("#{properties['application-host']}")
	private String			host;

	@Value("#{properties['unityUserInfoUri']}")
	private String			unityUserInfoUri;

	@Autowired
	private OauthService	oauthService;

	@RequestMapping(value = "authorization_code", method = RequestMethod.GET)
	public String authorizationCode(Model model) {
		model.addAttribute("userAuthorizationUri", userAuthorizationUri);
		model.addAttribute("host", host);
		model.addAttribute("unityUserInfoUri", unityUserInfoUri);
		model.addAttribute("state", UUID.randomUUID().toString());
		return "authorization_code";
	}

	/*
	 * 跳转到认证登录页面
	 */
	@RequestMapping(value = "authorization_code", method = RequestMethod.POST)
	public String submitAuthorizationCode() throws Exception {
		AuthorizationCodeDto codeDto = new AuthorizationCodeDto();
		codeDto.setClientId("unity-client");
		codeDto.setClientSecret("unity");
		codeDto.setRedirectUri(host + "authorization_code_callback");
		codeDto.setResponseType("code");
		codeDto.setScope("read write");
		codeDto.setState(UUID.randomUUID().toString());
		codeDto.setUserAuthorizationUri(userAuthorizationUri);
		return oauthService.submitAuthorizationCode(codeDto);
	}

	/*
	 * 获得授权后返回的code，然后调用服务获得accessToken,最后获得资源API
	 */
	@RequestMapping(value = "authorization_code_callback")
	public void authorizationCodeCallback(AuthCallbackDto callbackDto) throws Exception {
		Map<String, Object> resultMap = oauthService.authorizationCodeCallback(callbackDto);
		UserDto userDto = (UserDto) resultMap.get("userDto");
		if ((boolean) resultMap.get("flag")) {
			if (userDto.error()) {
				System.out.println(userDto.getErrorDescription());
			} else {
				System.out.println(userDto.getUsername());
			}
		} else {
			System.out.println(userDto.getErrorDescription());
		}
	}

}
